/*
Give you  a function char* read4096(), return a string which has <= 4096 characters
If the string less than 4096 characters which means reached the end of file ”
Use API read4096(), write a function char* readline()
Requirement:
#1 readline() returns when reading ‘\n’ or ”;
#2 readline() may be called multiple times on a file, the return value  should be correct.
#3 readline() may return char array longer than 4096 chars.
*/
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>
#include <string>
#include <cstring>
using namespace std;

#define MAX_BUF_SIZE 20 


int read4096(FILE *fp, char *buffer)
{
    int size = fread(buffer, 1, MAX_BUF_SIZE, fp);     
    if (size != MAX_BUF_SIZE)
	    cout << "Read to End of file size: " << size  << " " << buffer << endl;
    return size;
}

char *readline(FILE *fp)
{
    cout << "readline" << endl;
    static char buf[MAX_BUF_SIZE];  
    static int index = 0;
    static bool END = false;
    
    if (END) return NULL;

    int bytes;
    string str;
    while(1) {
	if (index != 0)  {
		str += buf + index;
	    index = 0;
	}
    int bytes = read4096(fp, buf);
    if (bytes < MAX_BUF_SIZE) END = true;
	if (bytes == 0) {return (char *)str.c_str(); }
	for (index = 0; index < bytes; index++) {
	    if (buf[index] == '\n') {index++; return (char *)str.c_str();}
	    else str += buf[index];
	}
    }
} 

int main(int argc, char **argv)
{
    FILE *fp = fopen("3.txt", "rb");
    if (fp == NULL) cout << "Open File Fail\n" << endl;
    char *str = NULL;
    while (1) {
        str = readline(fp);
	    if (str == NULL || strlen(str) == 0) break;  
	        cout << str << endl;
    }
    return 0;
}
